package com.outsider.util;

import java.util.HashMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class DoubanUtil {
    private static final String MOVIE_SEARCH_URL="http://api.douban.com/v2/movie/search?q=";
    private static final String MOVIE_DETAIL_URL="https://api.douban.com/v2/movie/subject/";
    private static final HashMap<Integer, JSONObject> cache=new HashMap<>();
    
    public static Integer getMovieID(String title){
    	OkHttp3 okHttp3=OkHttp3.getInstance();
    	JSONObject json=JSONObject.parseObject(okHttp3.get(MOVIE_SEARCH_URL+title));
    	if (json.getInteger("total")>0){
    		JSONArray subject=json.getJSONArray("subjects");
    		return Integer.parseInt(subject.getJSONObject(0).getString("id"));
    	}
    	else
    		return null;

    }

	public static Double getRating(Integer ID) {
		JSONObject json = getDetail(ID);
		return json.getJSONObject("rating").getDouble("average");
	}
	
	
	public static JSONObject getDetail(Integer ID){
		JSONObject json = cache.get(ID);
		if (json == null) {
			OkHttp3 okHttp3 = OkHttp3.getInstance();
			json = JSONObject.parseObject(okHttp3.get(MOVIE_DETAIL_URL + ID));
			cache.put(ID, json);
		}
		return json;
	}

	public static String getTags(Integer ID) {
		JSONObject json = getDetail(ID);
		JSONArray tag=json.getJSONArray("genres");
		StringBuilder sb=new StringBuilder();
		for (int i=0;i<tag.size();i++){
			sb.append(tag.getString(i)+" ");
		}
		return sb.toString();
	}
}
